package com.cnit1818.mybatis.dialect;

/**
 * SqlServer方言实现
 *
 */
public class SqlServerDialect extends Dialect
{
    @Override
    public boolean supportsLimit()
    {
        return true;
    }

    @Override
    public boolean supportsLimitOffset()
    {
        return false;
    }

    @Override
    public String getLimitString(String sql, int skipResults, int maxResults)
    {
        if (skipResults > 0)
        {
            throw new UnsupportedOperationException("sqlserver has no offset");
        }

        return new StringBuffer(sql.length() + 8)
                .append(sql)
                .insert(getAfterSelectInsertPoint(sql), " top " + maxResults)
                .toString();
    }

    static int getAfterSelectInsertPoint(String sql)
    {
        int selectIndex = sql.toLowerCase().indexOf("select");
        final int selectDistinctIndex = sql.toLowerCase().indexOf("select distinct");
        return selectIndex + (selectDistinctIndex == selectIndex ? 15 : 6);
    }
}
